<template>
  <div class="ele-body">
    <!-- 表格 -->
    <div>
      <a-card :bordered="false">
        <ele-pro-table
          ref="table"
          row-key="scwId"
          :datasource="datasource"
          :columns="columns"
          :where="where"
          :scroll="{ x: 'max-content' }"
        >
          <!-- table上边工具栏 -->
          <template #toolbar>
            <a-space>
              <a-button type="primary" @click="queryWifiList()"  :loading='queryWifiListRefLoading' v-permission="['PROPERTY_DEVICELIST_MGR_SPRAYCAMERA_WIFIRELAY_GET_BUTTON']">
                <span>查询继电器列表</span>
              </a-button>
            </a-space>
          </template>

          <!-- table操作栏按钮 -->
          <template #bodyCell="{ column, record }">
            <!-- table操作栏按钮 -->
            <template v-if="column.key === 'action'">
              <a-space>
                <a @click="openEdit(record)" v-permission="['PROPERTY_DEVICELIST_MGR_SPRAYCAMERA_WIFIRELAY_EDIT_BUTTON']">修改</a>
                <a-divider type="vertical" v-any-permission-and="[['PROPERTY_DEVICELIST_MGR_SPRAYCAMERA_WIFIRELAY_EDIT_BUTTON'], ['PROPERTY_DEVICELIST_MGR_SPRAYCAMERA_WIFIRELAY_DEL_BUTTON', 'PROPERTY_DEVICELIST_MGR_SPRAYCAMERA_WIFIRELAY_DEBUG_BUTTON']]" />
                <div v-permission="['PROPERTY_DEVICELIST_MGR_SPRAYCAMERA_WIFIRELAY_DEL_BUTTON']">
                  <a-popconfirm title="确定要删除此记录吗？" @confirm="remove(record)">
                    <a class="ele-text-danger">删除</a>
                  </a-popconfirm>
                </div>
                <a-divider type="vertical" v-any-permission-and="[['PROPERTY_DEVICELIST_MGR_SPRAYCAMERA_WIFIRELAY_EDIT_BUTTON', 'PROPERTY_DEVICELIST_MGR_SPRAYCAMERA_WIFIRELAY_DEL_BUTTON'], ['PROPERTY_DEVICELIST_MGR_SPRAYCAMERA_WIFIRELAY_DEBUG_BUTTON']]" />
                <div v-permission="['PROPERTY_DEVICELIST_MGR_SPRAYCAMERA_WIFIRELAY_DEBUG_BUTTON']">
                  <a-dropdown>
                    <a class="ant-dropdown-link" @click.prevent>
                      调试<DownOutlined />
                    </a>
                    <template #overlay>
                      <a-menu>
                        <a-menu-item @click="openDebugModal(record, 1)">
                          <a>调试关闭</a>
                        </a-menu-item>
                        <a-menu-item @click="openDebugModal(record, 2)">
                          <a>调试打开</a>
                        </a-menu-item>
                      </a-menu>
                    </template>
                  </a-dropdown>
                </div>
              </a-space>
            </template>
          </template>
        </ele-pro-table>
      </a-card>
    </div>
    <!-- 编辑弹窗 -->
    <DeviceSprayCameraWifirelayEdit v-if="showEdit" v-model:visible="showEdit" :data="current" @done="reload" />

    <!-- 添加调试操作弹窗 -->
    <a-modal
      v-model:visible="debugModalVisible"
      :title="debugType === 1 ? '调试关闭' : '调试打开'"
      @ok="handleDebugSubmit"
      @cancel="handleDebugCancel"
    >
      <p>确定要{{ debugType === 1 ? '关闭' : '打开' }}此继电器吗？</p>
    </a-modal>

  </div>
</template>

<script>
import { h } from 'vue';
import { PlusOutlined } from '@ant-design/icons-vue';
import { DeviceSprayCameraWifirelayApi } from '@/api/property/spraycamera/DeviceSprayCameraWifirelayApi';
import DeviceSprayCameraWifirelayEdit from './spraycamera-wifirelay-edit.vue'
import { message } from 'ant-design-vue';
import {DeviceCommandDownQueueApi} from "@/api/property/DeviceCommandDownQueueApi";
export default {
  name: 'DeviceSprayCameraWifirelay',
  components: {
    PlusOutlined,
    DeviceSprayCameraWifirelayEdit
  },
  props: {
    data: Object
  },
  async mounted() {
  },
  data() {
    return {
      // 表格列配置
      columns: [
        {
          title: '继电器ID',
          dataIndex: 'relayid'
        },
        {
          title: '喷淋状态反馈',
          dataIndex: 'relaySwitch',
          customRender: function(row) {
            let color;
            if (row.text == 1) {
              color = '#ff4d4f';  // 关闭 - 红色
              return h('span', { style: { color: color } }, "关闭");
            } else if (row.text == 2) {
              color = '#52c41a';  // 打开 - 绿色
              return h('span', { style: { color: color } }, "打开");
            } else if (row.text == 3) {
              color = '#faad14';  // 等待 - 黄色
              return h('span', { style: { color: color } }, "等待");
            } else if (row.text == 4) {
              color = '#ff4d4f';  // 失败 - 红色
              return h('span', { style: { color: color } }, "失败");
            }
            return h('span', { style: { color: '#d9d9d9' } }, "未知");  // 未知 - 灰色
          }
        },
        {
          title: '识别牛状态',
          dataIndex: 'status',
          customRender: function(row) {
            let color = row.text == 2 ? '#52c41a' : '#ff4d4f';  // 已识别-绿色，未识别-红色
            if (row.text == 1) {
              return h('span', { style: { color: color } }, "未识别");
            } else if (row.text == 2) {
              return h('span', { style: { color: color } }, "已识别");
            }
            return h('span', { style: { color: '#d9d9d9' } }, "未知");
          }
        },
        {
          title: '继电器连接状态',
          dataIndex: 'link',
          customRender: function(row) {
            let color = row.text == 2 ? '#52c41a' : '#ff4d4f';  // 连接-绿色，断开-红色
            if (row.text == 1) {
              return h('span', { style: { color: color } }, "断开");
            } else if (row.text == 2) {
              return h('span', { style: { color: color } }, "连接");
            }
            return h('span', { style: { color: '#d9d9d9' } }, "未知");
          }
        },
        {
          title: '设备类型',
          dataIndex: 'deviceName'
        },
        {
          title: '是否标注',
          dataIndex: 'slot',
          customRender: function(row) {
            if (row.record.slot && row.record.slot.scsId) {
              return h('span', { style: { color: '#52c41a' } }, "已标注");
            } else {
              return h('span', { style: { color: '#ff4d4f' } }, "未标注");
            }
          }
        },
        {
          title: '操作',
          key: 'action',
          width: 280,
          align: 'center',
        }
      ],
      // 表格搜索条件
      where: {
        "recordId" : this.data.recordId
      },
      // 当前编辑数据
      current: null,
      // 是否显示编辑弹窗
      showEdit: false,
      queryWifiListRefLoading : false,
      queryWifiListRefTimer : false,
      debugModalVisible: false,
      debugType: 1, // 1: 关闭, 2: 打开
      currentDebugRecord: null
    };
  },
  methods: {
    /**
     * 搜索按钮
     *
     * @author cancan
     * @date 2025/03/02 22:29
     */
    reload() {
      this.selection = [];
      this.$refs.table.reload({ page: 1 });
    },

    /**
     * 重置搜索
     *
     * @author cancan
     * @date 2025/03/02 22:29
     */
    reset() {
      this.where.recordId = this.data.recordId;
      this.$nextTick(() => {
        this.reload();
      });
    },

    /**
     * 删除
     *
     * @author cancan
     * @date 2025/03/02 22:29
     */
    async remove(row) {
      const result = await DeviceSprayCameraWifirelayApi.delete({ scwId: row.scwId });
      message.success(result.message);
      this.reload();
    },

    /**
     * 打开新增或编辑弹窗
     *
     * @author cancan
     * @date 2025/03/02 22:29
     */
    openEdit(row) {
      this.current = row;
      this.showEdit = true;
    },
    datasource({ page, limit, where, orders }) {
      return DeviceSprayCameraWifirelayApi.findPage({ ...where, ...orders, pageNo: page, pageSize: limit });
    },
    checkProcess(sceneDictate, clearCallback, callback) {
      let params = {
        recordId: this.data.recordId,
        sceneDictate: sceneDictate
      };
      let result = DeviceCommandDownQueueApi.workingDetail(params);
      result
        .then(result => {
          if (!result || !result.dcdqId) { //处理完成了
            clearCallback && clearCallback(); //去掉菊花+清除循环调用
            callback && callback(); //用户自定义
          }
        })
        .catch(() => {
          clearCallback && clearCallback(); //去掉菊花+清除循环调用
        });
    },

    //查询wifi继电器 begin
    clearQueryWifiListRef(){
      this.queryWifiListRefLoading = false;
      clearInterval(this.queryWifiListRefTimer);
    },
    checkQueryWifiList(){
      let that = this;
      this.checkProcess(9, this.clearQueryWifiListRef, function(){
        that.reset();
      });
    },
    queryWifiList()
    {
      let workerDetailparams = {
        recordId: this.data.recordId,
        sceneDictate: 9
      };
      let that = this;
      let existWorkerResult = DeviceCommandDownQueueApi.workingDetail2(workerDetailparams);
      existWorkerResult
        .then(workResult => {
          console.log(workResult);
          if (!workResult || !workResult.dcdqId) { //处理完成了
            that.pushQueryWifiListCmd();
          } else {
            message.error('上一个配置还在推送中，请稍后重试');
            return;
          }
        })
        .catch((e) => {
          message.error(e);
        });
    },
    pushQueryWifiListCmd() {
      this.loading = true;
      let updateDataRecord = {
        updateData: JSON.stringify({
          old: '',
          update: ''
        }),
        recordId: this.data.recordId,
        templateCode: 'spraycamera',
        dictate : 9,
        sceneDictate : 9
      };
      let result = DeviceCommandDownQueueApi.add(updateDataRecord);
      result
        .then(result => {
          this.loading = false;
          message.success(result.message);

          this.queryWifiListRefLoading = true; //转圈
          this.queryWifiListRefTimer = setInterval(this.checkQueryWifiList, 5000);
        })
        .catch(() => {
          this.loading = false;
        });
    },
    //查询wifi继电器 end


    openDebugModal(record, type) {
      this.currentDebugRecord = record
      this.debugType = type
      this.debugModalVisible = true
    },

    handleDebugCancel() {
      this.debugModalVisible = false
      this.currentDebugRecord = null
    },

    async handleDebugSubmit() {
      try {
        if (!this.currentDebugRecord) return
        let that = this;
        this.loading = true;
        let updateDataRecord = {
          updateData: JSON.stringify({
            old: '',
            update: {
              action: this.debugType, // 1: 关闭, 2: 打开
              relayid : this.currentDebugRecord.relayid,
            }
          }),
          recordId: this.data.recordId,
          templateCode: 'spraycamera',
          dictate: 10,
          sceneDictate: 10
        }

        let result = DeviceCommandDownQueueApi.add(updateDataRecord);
        result
          .then(result => {
            that.loading = false;
            message.success(result.message);

            that.debugModalVisible = false
            that.currentDebugRecord = null
          })
          .catch(() => {
            that.loading = false;
          });
      } catch (error) {
        message.error('操作失败')
      }
    }

  }
};
</script>
